/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package wf3.kernel;

import acceso.hibernate.AQuery;
import acceso.hibernate.AccesoHibernate;
import acceso.servlet.Transa_Engine;
import acceso.util.WorkflowUtil;
import java.sql.SQLException;
import java.util.concurrent.LinkedBlockingQueue;
import org.hibernate.StatelessSession;
import wf3.hibernate.Aquery2;

/**
 *
 * @author romulogalindo
 */
//public class TransaManager extends Manager {
public class TransaManager extends Thread {

    private static LinkedBlockingQueue<Aquery2> lsPrincipal = null;
    private static StatelessSession session = null;
    private static boolean run = false;

    static {
        lsPrincipal = new LinkedBlockingQueue<>();
        session = AccesoHibernate.new_session();
    }

    public TransaManager() {
        run = true;
    }

    public static synchronized void putQuery(Aquery2 query) {
        lsPrincipal.add(query);
    }

    public static synchronized Aquery2 getQuery() throws InterruptedException {
        return lsPrincipal.take();
    }

    @Override
    public void run() {
        while (run) {
            try {
                AQuery query = null;
                Aquery2 query2 = null;
                Object obj = lsPrincipal.take();
                if (obj != null) {
                    query2 = ((Aquery2) obj);
                    if(session.connection().isClosed()){
                        session = AccesoHibernate.new_session();
                    }
                    
                    query = query2.getAquery(session);

                    try {
//                        System.out.println("@@:" + query.getQuery());
                        query.uniqueResult();
                    } catch (Exception ep) {
                        String msg = "Query[" + query.getQuery() + "]\nMensaje[" + ep.getMessage() + "::" + ep.getClass() + "]";
                        if (ep instanceof SQLException) {
                            msg = msg + "\n SQL:" + ((SQLException) ep).getSQLState() + "::" + ((SQLException) ep).getMessage();
                        }
                        Transa_Engine.Transa_Ins_tbexcept(query2.getId_frawor(), query2.getCo_pagina(), msg);
                    }
                    query = null;
                }
            } catch (Exception ep) {
//                Transa_Engine.Transa_Ins_tbexcept(140388, 0, ep.getMessage() + "::" + ep.getClass());
                System.out.println("Error al procesar la insercion:" + ep.getMessage());
                ep.printStackTrace();
            }
        }
    }

    public static void clean() {
        lsPrincipal.clear();
    }

}
